package servicebctp

import (
	"context"
	"fmt"
	"github.com/aberic/gnomon"
	"github.com/aberic/gnomon/log"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"gykjgit.dccnet.com.cn/chain/proto/chain/bctp"
)

// Chaincode  智能合约调用
func Chaincode(url string, in *bctp.ReqChaincode) (*bctp.Resp, error) {
	log.Info("Do chaincode url request:" + in.Url)
	resp, err := gnomon.GRPCRequestPools(url, func(conn *grpc.ClientConn) (i interface{}, err error) {
		// 创建grpc客户端
		cli := bctp.NewChaincodeClient(conn)
		// 客户端向grpc服务端发起请求
		return cli.Chaincode(context.Background(), in)
	})
	if nil == err {
		if response, ok := resp.(*bctp.Resp); ok {
			fmt.Println(response)
			if response.Result.Error != nil {
				return nil, fmt.Errorf("code: %d, error: %s", response.Result.Error.Code, response.Result.Error.Data)
			}
			return response, nil
		}
		return nil, fmt.Errorf("chaincode %s failed, can not tarns interface to response", in.Method)
	}
	return nil, errors.Wrap(err, fmt.Sprintf("Chaincode %s failed", in.Method))
}
